package com.lecture.java8.date;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Queue;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author luyn
 * @description
 * @Date 2020/9/25 14:28
 * @Version 1.0
 */
public class ConcurrentDateFormat {
    private final String format;
    private final Locale locale;
    private final TimeZone timeZone;
    private final Queue<SimpleDateFormat> queue = new ConcurrentLinkedQueue<>();

    public ConcurrentDateFormat(String format, Locale locale, TimeZone timeZone) {
        this.format = format;
        this.locale = locale;
        this.timeZone = timeZone;
        SimpleDateFormat simpleDateFormat = createInstance();
        queue.add(simpleDateFormat);
    }

    public static ConcurrentDateFormat of(String format) {
        return new ConcurrentDateFormat(format, Locale.getDefault(), TimeZone.getDefault());
    }

    public String format(Date date) {   
        SimpleDateFormat sdf = queue.poll();
        if (sdf == null) {
            sdf = createInstance();
        }
        String result = sdf.format(date);
        queue.add(sdf);
        return result;
    }

    private SimpleDateFormat createInstance() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, locale);
        simpleDateFormat.setTimeZone(timeZone);
        return simpleDateFormat;
    }

}
